#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <stdarg.h>
#include "log.h"

#ifdef THREAD_SAFE
	#ifdef _MSC_VER
		#include <Windows.h>
		static CRITICAL_SECTION	s_cs;
	#else
		#include <pthread.h>
		static pthread_mutex_t s_mutex;
	#endif	// _MSC_VER
#endif	// THREAD_SAFE


static char s_dir[MAX_PATH] = ".";


void init_log(const char *dir)
{
#ifdef THREAD_SAFE
	#ifdef _MSC_VER
		InitializeCriticalSection(&s_cs);
	#else
		pthread_mutex_init(&s_mutex, NULL);
	#endif	// _MSC_VER
#endif

	if (dir != NULL && dir[0] != '\0')
	{
#ifdef _MSC_VER
		strcpy_s(s_dir, sizeof(s_dir), dir);
#else
		strncpy(s_dir, dir, sizeof(s_dir));
#endif
	}
}


#ifdef _MSC_VER
void write_log(const char *__fmt, ...)
{
	char line[MAX_LOG_LEN] = { 0 };
	char strt[MAX_LOG_LEN] = { 0 };
	char filename[MAX_PATH] = { 0 };
	char filepath[MAX_PATH] = { 0 };

	va_list ap;
	va_start(ap, __fmt);
	vsprintf_s(line, sizeof(line), __fmt, ap);
	va_end(ap);

	// 当前时间
	time_t curtm = time(NULL);
	struct tm tm_struct;
	(void)localtime_s(&tm_struct, &curtm);
	(void)strftime(strt, sizeof(strt), "%X", &tm_struct);
	(void)strftime(filename, sizeof(filename), "%Y-%m-%d.log", &tm_struct);
	(void)sprintf_s(filepath, sizeof(filepath), "%s/%s", s_dir, filename);

#ifdef THREAD_SAFE
	EnterCriticalSection(&s_cs);
#endif

	FILE *pf = NULL;
	fopen_s(&pf, filepath, "a+");
	if (pf != NULL)
	{
		fprintf(pf, "%s %s\n", strt, line);
		fclose(pf);
		pf = NULL;
	}

#ifdef THREAD_SAFE
	LeaveCriticalSection(&s_cs);
#endif
}
#else
void write_log(const char *__fmt, ...)
{
	char line[MAX_LOG_LEN] = { 0 };
	char strt[MAX_LOG_LEN] = { 0 };
	char filename[MAX_PATH] = { 0 };
	char filepath[MAX_PATH] = { 0 };

    va_list ap;
    va_start(ap, __fmt);
    vsprintf(line, __fmt, ap);
    va_end(ap);

    // 当前时间
    time_t curtm = time(NULL);
    struct tm tm_struct;
    (void)localtime_r(&curtm, &tm_struct);
    (void)strftime(strt, sizeof(strt)-1, "%T", &tm_struct);
	(void)strftime(filename, sizeof(filename), "%Y-%m-%d.log", &tm_struct);
	(void)snprintf(filepath, sizeof(filepath), "%s/%s", s_dir, filename);

#ifdef THREAD_SAFE
	pthread_mutex_lock(&s_mutex);
#endif

    FILE *pf = fopen(filepath, "a+");
    if (pf != NULL)
    {
		fprintf(pf, "%s %s\n", strt, line);
		fclose(pf);
		pf = NULL;	
    }

#ifdef THREAD_SAFE
	pthread_mutex_unlock(&s_mutex);
#endif
}
#endif	// _MSC_VER






















